package com.shushan.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.common.ui.RefreshLayout;
import com.android.common.ui.UnScrollGrideView;
import com.android.common.ui.UnScrollListView;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.andview.refreshview.XRefreshView;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseFragment;
import com.shushan.base.Constants;
import com.shushan.home.adapter.TodayRecordAdapter;
import com.shushan.home.adapter.WhiteAppsAdapter;
import com.shushan.home.bean.TodayRecordBean;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.GetSmartTimeActivity;
import com.shushan.pages.GetSyncTimeActivity;
import com.shushan.pages.GetToysActivity;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.MyWrongTopicActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.ForegroundRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.RefreshHeader;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.ControlUtil;
import com.shushan.util.DialogUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ChildFragment
 * @Desciption: 孩子模式fragment
 * @author: yichaohua
 * @date: 2018-07-16
 */
public class ChildFragment extends BaseFragment implements View.OnClickListener,
        VerificationCodeView.OnCodeFinishListener, AdapterView.OnItemClickListener, RefreshLayout.OnRefreshListener, XRefreshView.XRefreshViewListener {

    private static final String TAG = "ChildFragment";

    private UnScrollGrideView scrollGrideView;
    private UnScrollListView scrollListView;
    private WhiteAppsAdapter whiteAppsAdapter;
    private TodayRecordAdapter todayRecordAdapter;
    private XRefreshView refreshView;
    private ImageView timeImageView;
    private ImageView toyImageView;
    private LinearLayout emptyLayout;
    private LinearLayout quitLayout;

    private LinearLayout toysConvertLayout;
    private LinearLayout mistakeLayout;
    private LinearLayout toysCenterLayout;
    private Dialog noVipDialog;
    private View divid;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int changeNum = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        Log.i(TAG,"onCreateView()");

        View view = inflater.inflate(R.layout.child_fragment, null);

        initView(view);

        boolean isEyeOpen = SharedPreferencesUtils.getBooleanDate(Constants.PROJECT_EYE_SWITCH_SHAREPREFERS_KEY);
        if(isEyeOpen){
            int eyeInterval = SharedPreferencesUtils.getIntDate(Constants.PROJECT_EYE_INTERVAL_SHAREPREFERS_KEY);
            ControlUtil.setEyeProjectAlarm(getActivity(),eyeInterval);
        }

        refreshView.startRefresh();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(noVipDialog != null){
            noVipDialog.dismiss();
        }

        DialogUtil.dismissParentSetDialog();
    }

    private void initView(View view) {
        emptyLayout = view.findViewById(R.id.child_empty_1ayout);
        refreshView = view.findViewById(R.id.child_main_refv);
        refreshView.setPullRefreshEnable(true);
        refreshView.setXRefreshViewListener(this);
        refreshView.setCustomHeaderView(new RefreshHeader(getActivity()));
        scrollGrideView = view.findViewById(R.id.child_main_gv);
        scrollGrideView.setOnItemClickListener(this);
        whiteAppsAdapter = new WhiteAppsAdapter(getActivity());
        scrollGrideView.setAdapter(whiteAppsAdapter);
        scrollListView = view.findViewById(R.id.child_main_lv);
        todayRecordAdapter = new TodayRecordAdapter(getActivity());
        scrollListView.setAdapter(todayRecordAdapter);
        timeImageView = view.findViewById(R.id.child_main_get_time_img);
        timeImageView.setOnClickListener(this);
        toyImageView = view.findViewById(R.id.child_main_get_toy_img);
        toyImageView.setOnClickListener(this);
        quitLayout = view.findViewById(R.id.child_main_quit_layout);
        quitLayout.setOnClickListener(this);
        toysConvertLayout = view.findViewById(R.id.child_main_toys_convert_layout);
        toysConvertLayout.setOnClickListener(this);
        mistakeLayout = view.findViewById(R.id.child_main_mistake_layout);
        mistakeLayout.setOnClickListener(this);
        divid = view.findViewById(R.id.child_main_lv_bottom_divid);
        toysCenterLayout = view.findViewById(R.id.child_main_get_toy_layout);
    }

    @Override
    public void onRefresh() {
        new GetAppListTask().execute();
        getTodayRecord();
    }

    @Override
    public void onRefresh(boolean isPullDown) {

    }

    @Override
    public void onLoadMore(boolean isSilence) {

    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.child_main_get_time_img:
                gotoGetTime();
                break;
            case R.id.child_main_get_toy_img:
                startActivity(GetToysActivity.class);
                break;
            case R.id.child_main_quit_layout:
                if(TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
                    SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,false);
                    ActivityStackManager.getActivityStackManager().popAllActivity();
                    return;
                }
                DialogUtil.showParentOutAppDialog(getActivity(),this,this);
                break;
            case R.id.btn_find_back_psw://返回桌面dialog：找回密码
                DialogUtil.showForgetPswDialog(getActivity(),this);
                break;
            case R.id.btn_cancel://返回桌面dialog：取消
                DialogUtil.dismissParentSetDialog();
                break;
            case R.id.iv_close_no_bg://忘记密码dialog：×
                DialogUtil.dismissDialog();
                break;
            case R.id.iv_client_phone_num://忘记密码dialog：客服电话
                dialCustom();
                break;
            case R.id.child_main_toys_convert_layout:
                if(!shuShanApplication.isVip()) {
                    showNoVipDialog();
                    return;
                }

                boolean allowConvert = SharedPreferencesUtils.getBooleanDate(Constants.ALLOW_CONVERT_SWITCH_SHAREPREFERS_KEY);
                if(!allowConvert){
                    showToast("尚未允许兑换玩具");
                    return;
                }

                startActivity(MyStarActivity.class);
                break;
            case R.id.child_main_mistake_layout:
                if(!shuShanApplication.isVip()) {
                    showNoVipDialog();
                    return;
                }

                startActivity(MyWrongTopicActivity.class);
                break;
            default:
                break;
        }
    }

    private void dialCustom() {
        try {
            super.setAllowBack(true);
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
            startActivity(intent);
            DialogUtil.dismissDialog();
            DialogUtil.dismissParentSetDialog();
        }catch (SecurityException se){
            se.printStackTrace();
            showToast("没有打电话权限");
        }
    }

    private void gotoGetTime() {
//        if(shuShanApplication.isGameOver()){
//            int paperId = SharedPreferencesUtils.getIntDate(Constants.GAME_PAPER_ID_SHAREPREFERS_KEY);
//            GamesFloatWindow gamesFloatWindow = new GamesFloatWindow(shuShanApplication);
//            gamesFloatWindow.setPaperId(paperId);
//            GamesWindowManager.setGamesFloatWindow(gamesFloatWindow);
//            GamesWindowManager.createGamesFloatWindow(shuShanApplication);
//
//            return;
//        }
//
//        if(((changeNum % 2) == 0) && (shuShanApplication.getZnlx() == 1)){
//            startActivity(GetSmartTimeActivity.class);
//        }else {
//            startActivity(GetSyncTimeActivity.class);
//        }
//
//        changeNum++;
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            setAllowBack(true);
            ActivityStackManager.getActivityStackManager().popAllActivity();
            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,false);
        }else {
            showToast("家长密码错误");
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(!SystemUtils.checkUsagePermission(getActivity())){
            showNoUsageDialog();
            return;
        }

        List<AppInfo> appInfoList = whiteAppsAdapter.getAppInfoList();
        AppInfo appInfo = appInfoList.get(position);

        super.setAllowBack(true);
        SystemUtils.startApp(getActivity(),appInfo.getPackageName());

        Intent intent = new Intent(getActivity(),ForegroundRTAService.class);
        intent.putExtra("paperId",-1);
        intent.putExtra("allowPackName",appInfo.getPackageName());
        intent.putExtra("allowAppLabel",appInfo.getLabel());
        intent.putExtra("isWhitePlay",true);

        getActivity().startService(intent);
    }


    private class GetAppListTask extends AsyncTask<Void,Void,List<AppInfo>> {

        @Override
        protected List<AppInfo> doInBackground(Void... voids) {
            List<AppInfo> appInfoList = SystemUtils.getUsePackages(true,getActivity());

            return appInfoList;
        }

        @Override
        protected void onPostExecute(List<AppInfo> appInfoList) {
            if(ToolUtils.isListEmpty(appInfoList)){
                return;
            }

            whiteAppsAdapter.setAppInfoList(appInfoList);
            whiteAppsAdapter.notifyDataSetChanged();
        }
    }

    public void getTodayRecord() {
        int currentChildId = BabyApplication.getInstance().getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.CHILD_HOME_INDEX);
        urlParse.putValue("child_id", currentChildId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();
                        refreshView.stopRefresh();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if(!TextUtils.isEmpty(data)){
                            try {
                                JSONObject jsonObject = new JSONObject(data);
                                boolean reward = jsonObject.optBoolean("reward",false);
                                if(reward){
                                    toysCenterLayout.setVisibility(View.VISIBLE);
                                    toyImageView.setVisibility(View.VISIBLE);
                                }else {
                                    toysCenterLayout.setVisibility(View.GONE);
                                    toyImageView.setVisibility(View.GONE);
                                }

                                List<TodayRecordBean> todayRecordBeanList = new ArrayList<TodayRecordBean>();

                                JSONArray jsonArray = jsonObject.optJSONArray("record");
                                if(jsonArray != null){
                                    for (int i = 0;i < jsonArray.length();i++){
                                        JSONObject object = jsonArray.optJSONObject(i);
                                        TodayRecordBean todayRecordBean = new TodayRecordBean();
                                        todayRecordBean.initByJson(object);
                                        todayRecordBeanList.add(todayRecordBean);
                                    }
                                }

                                if(ToolUtils.isListEmpty(todayRecordBeanList)){
                                    emptyLayout.setVisibility(View.VISIBLE);
                                    scrollListView.setVisibility(View.GONE);
                                    divid.setVisibility(View.GONE);
                                }else {
                                    emptyLayout.setVisibility(View.GONE);
                                    scrollListView.setVisibility(View.VISIBLE);
                                    divid.setVisibility(View.VISIBLE);

                                    todayRecordAdapter.setTodayRecordBeanList(todayRecordBeanList);
                                    todayRecordAdapter.notifyDataSetChanged();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            showToast("数据返回空");
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void showNoVipDialog() {
        if(noVipDialog == null){
            noVipDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
            noVipDialog.setContentView(R.layout.no_vip_dialog);

            Button openButton = noVipDialog.findViewById(R.id.no_vip_open_btn);
            openButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noVipDialog.dismiss();

                    startActivity(OpenVipSpendActivity.class);
                }
            });

            Button shareButton = noVipDialog.findViewById(R.id.no_vip_share_btn);
            shareButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noVipDialog.dismiss();

                    startActivity(InviteForFreeUseActivity.class);
                }
            });

        }

        if(!noVipDialog.isShowing()){
            noVipDialog.show();
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }
}
